<?php
namespace backend\models;

use common\models\User;
use yii\base\Model;
use yii\db\ActiveRecord;

class UserForm extends Model {
    public $username;
    public $repassword;
    public $password;
    public $email;
    public $role;

    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '登陆密码',
            'repassword' => '重复密码',
            'email' => '邮箱',
            'role' => '角色等级',
            'status' => '状态',
        ];
    }

    public function rules()
    {
        return [
            //验证不能为空
            [
                ['username', 'password', 'repassword' , 'email','role'],
                'required',
                'message' => '{attribute}不能为空'
            ],
            ['username', 'unique','targetClass' => '\common\models\User','message' => '{attribute}已存在'],

            //字符串长度验证
            [
                ['username'],
                'string',
                'min' => 5,
                'max' => 15,
                'tooShort' => '{attribute}长度请大于5个字符',
                'tooLong' => '{attribute}长度请小于15个字符',
            ],
            //密码重复验证
            [
                'repassword',
                'compare',
                'compareAttribute' => 'password',
                'message' => '两次密码不一致'
            ],
            //邮箱格式验证
            [
                'email',
                'email',
                'message' => '邮箱格式不正确'
            ],
            //正则验证  ['tel','match','pattern'=>'/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})?$/','message'=>"{attribute}邮箱输入有误."],
            //自动完成
            //去掉前后空格
            [['username', 'password', 'repassword' , 'email','role'], 'trim'],
            [['username', 'password', 'repassword' , 'email','role'], 'default'],
        ];
    }

    public function signUp()
    {
        if ( !$this->validate() ){
            return null;
        }
        $model = new User();
        $model->username = $this->username;
        $model->setPassword($this->password);
        $model->role = $this->role;
        $model->email = $this->email;
        $model->created_at = time();
        $model->updated_at = time();
        $flag = $model->save();
        return $flag;
    }
}